package leetcode.code1012;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int numDupDigitsAtMostN(int n) {
		int p = 10;
		int o = n;
		int[] nums = new int[p];
		while (n > 0) {
			nums[--p] = n % 10;
			n /= 10;
		}
		return o - f(nums, p, true, false, (1 << 10) - 1);
	}

	private int f(int[] nums, int p, boolean max, boolean isNum, int rest) {
		if (p == 10) {
			return isNum ? 1 : 0;
		}
		if (isNum && !max) {
			int n = Integer.bitCount(rest);
			int ans = 1;
			while (p < 10) {
				ans *= n;
				p++;
				n--;
			}
			return ans;
		}
		int ans = 0;
		if (!isNum) {
			ans += f(nums, p + 1, false, isNum, rest);
		}
		int low = !isNum ? 1 : 0;
		int up = max ? nums[p] : 9;
		for (int i = low; i <= up; i++) {
			if (((1 << i) & rest) != 0) {
				ans += this.f(nums, p + 1, i == nums[p] && max ? true : false, true, rest ^ (1 << i));
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(1, this.numDupDigitsAtMostN(20));
		H.compare(10, this.numDupDigitsAtMostN(100));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
